/**
 * This is a class to run the game of tic-tac-toe.  It will be used by
 * the tic-tac-toe driver, TTTDriver. The code here may be useful for
 * providing hints as to how your TTTBoard, HumanPlayer, DumbPlayer,
 * and SmartPlayer classes must work.
 * 
 * !!!!! DO NOT MODIFY THIS FILE !!!!!
 */

public class TTTEngine
{
	
	private boolean VERBOSE; 
	
	private TTTBoard board;
	private int winner;
	
	public TTTEngine(){
		this.board = new TTTBoard(4);
		//this.board = new TTTBoard();
		this.winner = -1;
		this.VERBOSE = false;
	}
	
	public TTTEngine(boolean useVerbose)
	{
		this();
		if (useVerbose)
			this.VERBOSE = true;
	}
	
	public void startGame(TTTPlayer p1, TTTPlayer p2)
	{
		TTTMove move;
		board.clearBoard();
		if (VERBOSE)
			board.printBoard();
		display();
		
		while (true)
		{
			display("Player 1's turn (" + board.getPlayerMark(TTTBoard.PLAYER_1) + ")");
			move = p1.getMove(board, TTTBoard.PLAYER_1);
			board.applyMove(move);
			display("Player 1 marked " + move);
			display();
			if (VERBOSE)
				board.printBoard();
			display();
			if (board.gameIsOver())
				break;
			
			display("Player 2's turn (" + board.getPlayerMark(TTTBoard.PLAYER_2) + ")");
			move = p2.getMove(board, TTTBoard.PLAYER_2);
			board.applyMove(move);
			display("Player 2 marked " + move);
			display();
			if (VERBOSE)
				board.printBoard();
			display();
			if (board.gameIsOver())
				break;
			
		}
		
		if (board.isWin(TTTBoard.PLAYER_1))
		{
			display("Player 1 wins!");
			winner = TTTBoard.PLAYER_1;
		}
		else if (board.isWin(TTTBoard.PLAYER_2))
		{
			display("Player 2 wins!");
			winner = TTTBoard.PLAYER_2;
		}
		else
		{
			display("It's a draw.");
			winner = 0;
		}
	}
	
	public int getWinner() { return winner; }
	
	public void display(String str)
	{
		if (VERBOSE)
			System.out.println(str);
	}
	
	public void display() { display(""); }

}
